/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 */
package seedpod.webapp.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seedpod.exceptions.DataValidationException;
import seedpod.exceptions.SeedpodException;
import seedpod.model.AVPair;
import seedpod.model.SeedpodDO;
import seedpod.rdb.PMFactory;
import seedpod.rdb.PManager;
import seedpod.util.Util;
import seedpod.webapp.LimsSession;
import seedpod.webapp.Seedpod;
import seedpod.webapp.view.InstanceRenderer;

public class ActionEditInstance extends HttpServlet {

	private static final long	serialVersionUID	= -1382509010699123214L;
	public static final String	URL					= "editInstance";

	public static String getUrl( int oid ) {
		return URL + "?" + InstanceRenderer.OID + "=" + oid;
	}

	private String		_clsName;
	private int			_oid;
	private SeedpodDO	_object;

	private PManager	_manager;

	@Override
	public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
	// DO NOTHING
	}

	@Override
	public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String displayUrl;
		String pageMsg = "";
		LimsSession spSession = LimsSession.getSession( request );
		HashMap<String, DataValidationException> validationErr = new HashMap<String, DataValidationException>();

		if ( _manager == null ) {
			out.println( "Cannot connect to the database. " );
			return;
		}

		initRequiredField( request );

		// class name and oid must be defined
		if ( _clsName == null || _oid == 0 ) {
			pageMsg = "This object doesn't exist in the database " + _clsName + " " + _oid;
			spSession.setAttribute( InstanceRenderer.PAGE_MSG, pageMsg );
			out.println( pageMsg );
			return;
		}

		// get object from session cache or the database
		_object = (SeedpodDO)spSession.getAttribute( Util.getSeedpodInternalId( _clsName, _oid ) );
		if ( _object == null ) {
			_object = _manager.createObject( _clsName, _oid );
			System.err.println( "I found an object in the database " );
		} else System.err.println( "I found an object in the session! :) " );

		_object.markDirty();
		ArrayList<AVPair> avpairs = _object.getAttributeValues();
		for ( AVPair avpair : avpairs ) {
			Object submittedValue = request.getParameter( avpair.genRefId() );
			avpair.setValue( submittedValue );

			try {
				avpair.validate();
			} catch (DataValidationException e) {
				validationErr.put( avpair.genRefId(), e );
			}
		}
		spSession.setAttribute( Util.getSeedpodInternalId( _clsName, _oid ), _object );
		displayUrl = "lims/instance.jsp?" + InstanceRenderer.CLSNAME + "=" + _clsName;
		displayUrl += "&" + InstanceRenderer.OID + "=" + _oid;

		if ( validationErr.size() == 0 ) // SAVE to the Database
		try {
			// manager.makePersistent( _object );
			_object.makePersist();
			pageMsg = "Changes saved.";

			displayUrl += "&" + InstanceRenderer.ACTION + "=" + InstanceRenderer.ACTION_VIEW;
			displayUrl = Seedpod.getAbsoluteUrl( displayUrl );
			Util.redirect( displayUrl, request, response );
		} catch (SeedpodException e) {
			pageMsg = e.getMessage();
			out.println( pageMsg );
		}
		else if ( validationErr.size() > 0 ) {
			pageMsg = "Please correct the following error(s).";
			spSession.setAttribute( InstanceRenderer.VALIDATION_ERROR, validationErr );

			displayUrl += "&" + InstanceRenderer.ACTION + "=" + InstanceRenderer.ACTION_EDIT;
			displayUrl = Seedpod.getAbsoluteUrl( displayUrl );
			Util.redirect( displayUrl, request, response );
		}

		spSession.setAttribute( InstanceRenderer.PAGE_MSG, pageMsg );
	}

	@Override
	public void init() {
		try {
			PMFactory factory = Seedpod.getPersistenceManagerFactory();
			_manager = factory.createManager();
		} catch (SeedpodException se) {
			System.err.println( " Cannot find valid Persistence Manager. " + se.getMessage() );
		}
	}

	private void initRequiredField( HttpServletRequest request ) {
		/** required variables * */
		String oidStr = request.getParameter( InstanceRenderer.OID );
		_clsName = request.getParameter( InstanceRenderer.CLSNAME );
		_oid = oidStr != null ? Integer.decode( oidStr ) : 0;
	}
}
